package com.youkeda.test.http;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

/**
 * @author CoderXshuai
 */
public class PageAsker {

    public static void main(String[] args) {
        String url = "https://www.douban.com/mine";
        PageAsker asker = new PageAsker();
        String content = asker.getContent(url);
        System.out.println(content);
    }

    /**
     * 根据输入的url，读取页面内容并返回
     */
    public String getContent(String url) {
        // okHttpClient 实例
        OkHttpClient okHttpClient = new OkHttpClient();
        // 定义一个request
        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36")
                .addHeader("Referer", "https://www.douban.com")
                .addHeader("Host", "www.douban.com")
                .addHeader("Cookie", ReadFileTool.readContent("cookie.txt"))
                .build();
        // 返回结果字符串
        String result = "";
        try {
            // 执行请求
            Response response = okHttpClient.newCall(request).execute();
            result = response.body().string();
        } catch (IOException e) {
            System.out.println("request " + url + " error . ");
            e.printStackTrace();
        }
        return result;
    }
}
